package org.csu.small.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.net.ftp.FTPClient;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * @author SongYaolun
 * @version 1.0
 * @date 2020/7/5 11:35
 */
public class FTPUtil {
    private static final Logger logger = LoggerFactory.getLogger(FTPUtil.class);

    private static String ftpIp = PropertiesUtil.getProperty("ftp.server.ip");
    private static String ftpUser = PropertiesUtil.getProperty("ftp.user");
    private static String ftpPass = PropertiesUtil.getProperty("ftp.pass");
    private static String imageHostUrl = PropertiesUtil.getProperty("ftp.server.http.prefix");//ftp服务器地址的前缀
//
    public FTPUtil(String ip, int port, String user, String pwd) {
        this.ip = ip;
        this.port = port;
        this.user = user;
        this.pwd = pwd;
    }


    /**
     * =====================唯一向外暴露的方法===================
     * 返回上传成功、或者失败（可以批量上传）
     * @param fileList
     * @return
     * @throws IOException
     */
    public static boolean uploadFile(List<File> fileList) throws IOException {
        FTPUtil ftpUtil = new FTPUtil(ftpIp, 21, ftpUser, ftpPass);
        logger.info("开始连接ftp服务器，上传开始，服务器地址:{}", ftpIp);
        //boolean result = ftpUtil.uploadFile("img", fileList);   //意思就是上传到ftp服务器的img文件夹下

        String remotePath = "/ftp/image";
        boolean result = ftpUtil.uploadFile(remotePath, fileList);   //意思就是上传到ftp服务器的 img 文件夹下,可以切换
        logger.info("结束连接ftp服务器,结束上传,上传结果:{}，上传至服务器路径为:{}", result == true ? "上传成功！" : "上传失败！", imageHostUrl);
        return result;
    }


    /**
     * 上传逻辑封装，不予暴露
     * @param remotePath    远程路径，因为服务器的路径可能不同
     * @param fileList
     * @return
     * @throws IOException
     */
    private boolean uploadFile(String remotePath, List<File> fileList) throws IOException {
        boolean uploaded = true;
        FileInputStream fis = null;
        //连接FTP服务器
        if (connectServer(this.ip, this.port, this.user, this.pwd)) {
            try {
                //1、更改工作目录，即需不需要切换文件夹
                ftpClient.changeWorkingDirectory(remotePath);
                //2、设置缓冲区
                ftpClient.setBufferSize(1024);
                //3、设置编码字符集
                ftpClient.setControlEncoding("UTF-8");
                //4、文件类型设置为二进制类型，防止乱码问题，FTPClient.BINARY_FILE_TYPE是它提供的一个常量
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                //5、打开本地的被动模式
                ftpClient.enterLocalPassiveMode();
                //6、上传
                for (File fileItem : fileList) {
                    fis = new FileInputStream(fileItem);
                    ftpClient.storeFile(fileItem.getName(), fis);
                }

            } catch (IOException e) {
                logger.error("************Ftp上传文件异常*************", e);
                uploaded = false;
                e.printStackTrace();
            } finally {
                //7、一定记得关闭流、和释放连接
                fis.close();
                ftpClient.disconnect();
            }
        }
        return uploaded;
    }

    /**
     * 连接远程服务器
     * @param ip    IP地址
     * @param port  端口
     * @param user  用户
     * @param pwd   密码
     * @return
     */
    private boolean connectServer(String ip, int port, String user, String pwd) {

        boolean isSuccess = false;
        ftpClient = new FTPClient();
        try {
            ftpClient.connect(ip);
            isSuccess = ftpClient.login(user, pwd);
        } catch (IOException e) {
            logger.error("连接FTP服务器异常", e);
        }
        return isSuccess;
    }


    private String ip;
    private int port;
    private String user;
    private String pwd;
    private FTPClient ftpClient;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public FTPClient getFtpClient() {
        return ftpClient;
    }

    public void setFtpClient(FTPClient ftpClient) {
        this.ftpClient = ftpClient;
    }
}
